<?php

declare(strict_types=1);

namespace app\controller\api;


use app\util\Sms;
use think\facade\Db;
use think\Response;
use app\util\WechatService;

/**
 * 驾校用户
 */
class JxUser extends Base
{

    //获取短信验证码
    public function getPhoneCode(): Response
    {
        $sms = new Sms();
        $param = $this->request->param();
        $phone = $param['phone']; //手机号
        if (empty($phone)) {
            return $this->buildFailed(400, '参数不正确');
        }
        $code = rand(1000, 9999);
        //发送短信
        $sems_data = Db::table('jx_sms')->where('phone', $phone)->find();
        if ($sems_data) {
            Db::table('jx_sms')->where('phone', $phone)->delete();
        }
        $data['phone'] = $phone;
        $data['code'] = $code;
        $data['addtime'] = date('Y-m-d H:i:s', time());
        $id = Db::table('jx_sms')->save($data);
        $resB = $sms->sendSms($phone, $code);
        return $this->buildSuccess([]);
    }

    //用户登录
    public function login(): Response
    {
        $param = $this->request->param();
        $code  = $param['code']; //微信code
        if (empty($code)) {
            return $this->buildFailed(400, 'code不能为空');
        }
        $wechat = new WechatService;
        $result = $wechat->wechatXcx()->auth->session($code);
        if (!empty($result['openid'])) {
            $openid = $result['openid'];
        } else {
            return $this->buildFailed(400, 'code错误');
        }
        //已注册！直接验证账号信息进行登录
        $map['open_id'] = $openid;
        $map['status'] = array('in', '1,2');
        $userData = Db::name('jx_users')->where($map)->find();
        if (empty($userData)) {
            $add['nickname'] = '微信用户' . rand(1, 999999); //用户昵称
            $add['user_img'] = "https://" . $_SERVER['SERVER_NAME'] . "/public/images/user_img.png"; //用户头像
            $add['open_id'] = $openid; //微信openID
            $add['add_time'] = date("Y-m-d H:i:s"); //注册时间
            $add['id'] = Db::name('jx_users')->insertGetId($add);
        } else {
            if ($userData['status'] == 2) {
                return $this->buildFailed(400, '账号被禁用');
            }
        }
        return $this->buildSuccess(['result' => $userData]);
    }
    //修改用户信息
    public function updateUser(): Response
    {
        $param = $this->request->param();
        if (isset($param['user_id']) && $param['user_id'] == '') {
            return $this->buildFailed(400, 'user_id 参数错误');
        }
        if (isset($param['user_img']) && $param['user_img'] != '') {
            $map['user_img'] = $param['user_img'];
        }

        if (isset($param['nickname']) && $param['nickname'] != '') {
            $map['nickname'] = $param['nickname'];
        }
        if (isset($param['phone']) && $param['phone'] != '') {
            $map['user_phone'] = $param['phone'];
        }
        if (isset($param['user_name']) && $param['user_name'] != '') {
            $map['user_name'] = $param['user_name'];
        }
        if (isset($param['sex']) && $param['sex'] != '') {
            $map['sex'] = $param['sex']; //1男 2女
        }
        if (isset($param['Id_card']) && $param['Id_card'] != '') {
            $map['Id_card'] = $param['Id_card']; //用户身份证号
        }
        $map['update_time'] = date('Y-m-d H:i:s', time());
        $res = Db::name('jx_users')->where('id', $param['user_id'])->save($map);
        return $this->buildSuccess();
    }

    //获取用户信息
    public function getUserInfo(): Response
    {
        $param = $this->request->param();
        if (isset($param['user_id']) && $param['user_id'] == '') {
            return $this->buildFailed(400, 'user_id 参数错误');
        }
        $field  = 'id,user_img,nickname,user_name,sex,Id_card,open_id,user_phone,is_student,balance,is_coach,status';
        $userInfo = Db::table('jx_users')->where('id', $param['user_id'])->field($field)->find();
        return $this->buildSuccess($userInfo);
    }

    //用户绑定新的手机号
    public function userBindPhone(): Response
    {
        $param = $this->request->param();
        if (isset($param['user_id']) && $param['user_id'] == '') {
            return $this->buildFailed(400, 'user_id 参数错误');
        }
        if (isset($param['phone']) && $param['phone'] != '') {
            $map['phone'] = $param['phone'];  //手机号
        }
        if (isset($param['code']) && $param['code'] != '') {
            $map['code'] = $param['code'];  //code 码
        }
        $row = Db::name('jx_sms')->where($map)->find();
        if (empty($row)) {
            return $this->buildFailed(401, '手机号验证错误');
        }
        $userPhoneMap['user_phone'] = $param['phone'];
        $userPhoneMap['status'] = array('in', '1,2');
        $userInfo = Db::table('jx_users')->where($userPhoneMap)->find();
        if (!empty($userInfo)) {
            return $this->buildFailed(402, '该手机号已经被绑定，请更换手机号');
        }
        $res = Db::table('jx_users')->where('id', $param['user_id'])->save(['user_phone' => $param['phone']]);
        if ($res) {
            return $this->buildSuccess();
        } else {
            return $this->buildFailed(403, '绑定失败');
        }
    }

    //获取通知列表
    public function userNotceList(): Response
    {
        $param = $this->request->param();
        if (isset($param['user_id']) && $param['user_id'] == '') {
            return $this->buildFailed(400, 'user_id 参数错误');
        }
        $page = isset($param['page']) && ($param['page'] != '') ? $param['page'] : 1;
        $limit =  isset($param['limit']) && ($param['limit'] != '') ? $param['limit'] : 10;
        $list = Db::table('jx_notice')->page((int)$page, (int)$limit)->select();
        $count = Db::table('jx_notice')->count();
        $data['list'] = $list;
        $data['count'] = $count;
        if ($data) {
            return $this->buildSuccess($data);
        } else {
            return $this->buildFailed(401, '获取数据失败');
        }
    }

    /**
     * 上传图片
     */
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $files = request()->file();
        $savename = '';
        try {
            validate(['image' => 'fileSize:50240|fileExt:jpg,png'])
                ->check($files);
            $savename = '';
            foreach ($files as $file) {
                $savename = \think\facade\Filesystem::disk('public')->putFile('upload/image', $file);
                $code = 1;
                $mes = '成功';
            }
        } catch (\think\exception\ValidateException $e) {
            $mes = $e->getMessage();
            $code = 0;
        }
        return json(['code' => $code, 'url' => '/storage/' . $savename, 'mes' => $mes]);
    }

    //成为教练
    public function becomeCoach(): Response
    {
        $param = $this->request->param();
        if (isset($param['user_id']) && $param['user_id'] == '') {
            return $this->buildFailed(400, 'user_id 参数错误');
        }
        if (isset($param['user_name']) && $param['user_name'] != '') {
            $map['user_name'] = $param['user_name'];
        }

        if (isset($param['Id_card']) && $param['Id_card'] != '') {
            $map['Id_card'] = $param['Id_card'];
        }
        if (isset($param['drive_age']) && $param['drive_age'] != '') {
            $map['drive_age'] = $param['drive_age'];
        }
        if (isset($param['address']) && $param['address'] != '') {
            $map['address'] = $param['address'];
        }
        $where['user_id'] = $param['user_id'];
        $where['Id_card'] = $param['Id_card'];

        $data = Db::table('jx_dream_coach_record')->where($where)->find();
        if (!empty($data)) {
            return $this->buildFailed(402, '您已经成为教练，无须重复添加');
        }
        $map['user_id'] = $param['user_id'];
        $map['add_time'] = date('Y-m-d H:i:s', time());
        $res = Db::table('jx_dream_coach_record')->insert($map);
        if ($res) {
            return $this->buildSuccess();
        } else {
            return $this->buildFailed(401, '获取数据失败');
        }
    }

    //获取证件名称列表
    public function getCertificateList(): Response
    {
        $param = $this->request->param();
        if (isset($param['user_id']) && $param['user_id'] == '') {
            return $this->buildFailed(400, 'user_id 参数错误');
        }
        $page = isset($param['page']) && ($param['page'] != '') ? $param['page'] : 1;
        $limit =  isset($param['limit']) && ($param['limit'] != '') ? $param['limit'] : 10;
        $data['list'] = Db::table('jx_certificate')->page((int)$page, (int)$limit)->select();
        $data['conut'] = Db::table('jx_certificate')->count();
        if ($data) {
            return $this->buildSuccess($data);
        } else {
            return $this->buildFailed(401, '获取数据失败');
        }
    }
    //办证大厅，办理证件
    public function handleCertificate(): Response
    {
        $param = $this->request->param();
        if (isset($param['user_id']) && $param['user_id'] == '') {
            return $this->buildFailed(400, 'user_id 参数错误');
        }
        if (isset($param['certificate_id']) && $param['certificate_id'] != '') {
            $certificate_id = $param['certificate_id']; //证件id
            $map['certificate_id'] =  $certificate_id;
        }

        if (isset($param['user_name']) && $param['user_name'] != '') {
            $map['user_name'] = $param['user_name'];
        }
        if (isset($param['user_phone']) && $param['user_phone'] != '') {
            $map['user_phone'] = $param['user_phone'];
        }
        $where['user_name'] = $param['user_name'];
        $where['user_phone'] = $param['user_phone'];

        $data = Db::table('jx_user_certificate')->where($where)->find();
        if (!empty($data)) {
            return $this->buildFailed(402, '您已经办理证件');
        }
        $map['user_id'] = $param['user_id'];
        $map['add_time'] = date('Y-m-d H:i:s', time());
        $res = Db::table('jx_user_certificate')->insert($map);
        if ($res) {
            return $this->buildSuccess();
        } else {
            return $this->buildFailed(401, '获取数据失败');
        }
    }

    //轮播图列表
    public function homeBannerList(): Response
    {
        $param = $this->request->param();
        $page = isset($param['page']) && ($param['page'] != '') ? $param['page'] : 1;
        $limit =  isset($param['limit']) && ($param['limit'] != '') ? $param['limit'] : 10;
        $where['status'] = array('in', '1,2');
        $list = Db::table('jx_banners')->page((int)$page, (int)$limit)->where($where)->order('id desc')->select();
        $count = Db::table('jx_banners')->where($where)->count();
        $data['list'] = $list;
        $data['count'] = $count;
        if ($data) {
            return $this->buildSuccess($data);
        } else {
            return $this->buildFailed(401, '获取数据失败');
        }
    }

    //成为学生
    public function becomeStudent(): Response
    {
        $param = $this->request->param();
        if (isset($param['user_id']) && $param['user_id'] == '') {
            return $this->buildFailed(400, 'user_id 参数错误');
        }
        if (isset($param['user_name']) && $param['user_name'] != '') {
            $map['user_name'] = $param['user_name'];
        }

        if (isset($param['Id_card']) && $param['Id_card'] != '') {
            $map['Id_card'] = $param['Id_card'];
        }
        if (isset($param['user_phone']) && $param['user_phone'] != '') {
            $map['user_phone'] = $param['user_phone'];
        }
        if (isset($param['student_img']) && $param['student_img'] != '') {
            //多个图片，可为JSON传["1.jpg","2.jpg"];
            $map['student_img'] = $param['student_img'];
        }
        $where['user_id'] = $param['user_id'];
        $where['Id_card'] = $param['Id_card'];

        $data = Db::table('jx_student_authentication')->where($where)->find();
        if (!empty($data)) {
            return $this->buildFailed(402, '您已经成为教练，无须重复添加');
        }
        $map['user_id'] = $param['user_id'];
        $map['add_time'] = date('Y-m-d H:i:s', time());
        $res = Db::table('jx_student_authentication')->insert($map);
        if ($res) {
            return $this->buildSuccess();
        } else {
            return $this->buildFailed(401, '获取数据失败');
        }
    }

    //学生申请详情
    public function studentDetail(): Response
    {
        $param = $this->request->param();
        $user_id = isset($param['user_id']) && ($param['user_id'] != '') ? $param['user_id'] : 0;
        if ($user_id == 0) {
            return $this->buildFailed(402, '学生id不能为空');
        }

        $row = Db::table('jx_student_authentication')->where('user_id', $user_id)->find();
        if (!empty($row)) {
            $row['student_img'] = json_decode($row['student_img'], true);
        }
        $data['result'] = $row;
        if ($data) {
            return $this->buildSuccess($data);
        } else {
            return $this->buildFailed(401, '获取数据失败');
        }
    }



}
